package routers

import (
	"encoding/json"
	"errors"
	"gitee.com/phpdi/ant-api/controllers"
	"gitee.com/phpdi/ant-api/entitys"
	"gitee.com/phpdi/ant-api/services"
	"gitee.com/phpdi/ant-api/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"strings"
)

//未登录可访问的url
var openUrl=[]string{
	"login/login",
}


func init() {
	beego.AutoRouter(&controllers.LoginController{})
	beego.AutoRouter(&controllers.UserController{})


	//登录,权限验证过滤器
	beego.InsertFilter("/*",beego.BeforeRouter,func(ctx *context.Context) {
		curUrl:=getCurtPerm(ctx)
		//未登录可访问的url
		if utils.InArray(curUrl, openUrl) {
			return
		}

		//需要登录,检查权限
		if !services.PermService.HasPerm(getAuthUser(ctx),curUrl) {
			checkErr(ctx,errors.New("权限拒绝"))
		}

	})


}


//根据路由获取当前权限判定数据
func getCurtPerm(ctx *context.Context)(permUrl string) {
	urlArr := strings.Split(ctx.Request.URL.Path, "/")
	if len(urlArr) < 2 {
		return
	}

	return urlArr[len(urlArr)-2]+"/"+urlArr[len(urlArr)-1]
}

//通过ctx 获取出登录用户
func getAuthUser(ctx *context.Context)(user  entitys.User) {

	token:=ctx.Input.Header("Token")

	if token== "" {

		checkErr(ctx,errors.New("token 不能为空"))

		return
	}

	auth:=services.NewAuth()
	err:=auth.SetUserByToken(token)
	checkErr(ctx,err)


	return auth.GetUser()
}

func checkErr(ctx *context.Context,err error)  {
	if err!= nil {
		jsonStr,_:=json.Marshal(entitys.JsonResult{
			Code:entitys.CodeErr,
			Msg:err.Error(),
		})
		ctx.WriteString(string(jsonStr))

	}

}